// miniprogram/pages/addTodo/addTodo.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const db = wx.cloud.database();
const app = getApp();
const movements = db.collection('movements')
Page({
  data: {
    picSwitch: false,
    tempFilePaths: [],
    picUrls: [],
    title: '',
    input: '',
    price: '',
    college: '',
    phone: '',
    popup: false,
    collegeName: '学院名称',
    colleges: [
      ["传播学院", "media"],
      ["体育部", "sport"],
      ["信息工程学院", "information"],
      ["光电工程学院", "photoelectricity"],
      ["化学与化工学院", "chemistry"],
      ["医学院", "medicine"],
      ["国际交流学院", "international"],
      ["土木工程学院", "construction"],
      ["外国语学院", "language"],
      ["师范学院", "normal"],
      ["建筑与城市规划学院", "building"],
      ["成人教育学院", "adult"],
      ["数学与计算科学学院", "math"],
      ["文学院", "literature"],
      ["机电与控制工程学院", "machine"],
      ["材料学院", "material"],
      ["法学院", "law"],
      ["物理科学与技术学院", "physics"],
      ["生命科学学院", "biology"],
      ["电子科学与技术学院", "eletronic"],
      ["研究生部", "master"],
      ["管理学院", "manage"],
      ["经济学院", "economy"],
      ["艺术设计学院", "art"],
      ["计算机与软件学院", "computer"],
      ["高尔夫学院", "golf"],
    ]
  },

  onLoad: function (event) {
    this.setData({
      college: event.prof
    })
    var colleges = this.data.colleges
    for (var i = 0; i < colleges.length; i++) {
      if (colleges[i][1] == event.prof) {
        this.setData({
          collegeName: colleges[i][0]
        })
        break
      }
    }
  },

  ChooseImg: function () {
    let that = this;
    wx.chooseImage({
      count: 9, // 默认最多9张图片，可自行更改
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePath = res.tempFilePaths;
        that.setData({
          tempFilePaths: tempFilePath
        })
      }
    })
  },

  //预览图片
  PreviewImg: function (e) {
    let index = e.target.dataset.index;
    let that = this;
    //console.log(that.data.tempFilePaths[index]);
    //console.log(that.data.tempFilePaths);
    wx.previewImage({
      current: that.data.tempFilePaths[index],
      urls: that.data.tempFilePaths,
    })
  },
  //长按删除图片
  DeleteImg: function (e) {
    var that = this;
    var tempFilePaths = that.data.tempFilePaths;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          //console.log('点击确定了');
          tempFilePaths.splice(index, 1);
        } else if (res.cancel) {
          //console.log('点击取消了');
          return false;
        }
        that.setData({
          tempFilePaths
        });
      }
    })
  },

  bindInput: function (event) {
    this.setData({
      input: event.detail.value
    })
  },

  onTitleChange(event) {
    // event.detail 为当前输入的值
    if (event.detail.length > 15) {
      wx.showToast({
        title: '标题字数不超过15个哦',
        icon: 'none'
      })
    } else {
      this.setData({
        title: event.detail
      })
    }
  },

  onPriceChange(event) {
    // event.detail 为当前输入的值
    this.setData({
      price: event.detail
    })
  },

  onPhoneChange(event) {
    // event.detail 为当前输入的值
    this.setData({
      phone: event.detail
    })
  },

  myEventListener: function (e) {
    console.log("上传的图片结果集合")
    console.log(e.detail.picsList)
  },

  //图片
  switch2Change: function (event) {
    this.setData({
      picSwitch: event.detail.value,
      detailPic: ''
    })
  },

  onClickLeft() {
    Dialog.confirm({
        title: '退出编辑',
        message: '确认要退出编辑吗？',
      })
      .then(() => {
        // on confirm
        wx.navigateBack()
      })
      .catch(() => {
        // on cancel
        wx.showToast({
          title: '留在编辑页',
          icon: 'none'
        });
      });
  },

  onClickRight() {
    if (this.data.input == '' || this.data.phone == '' || this.data.price=='' || this.data.title == '') {
      wx.showModal({
        title: '输入不为空！',
        cancelColor: 'cancelColor',
        success: res => {
          if (res.cancel)
            return
        }
      })
    } else {
      wx.showLoading({
        title: '正在提交',
      })

      var count = 0;
      var length = this.data.tempFilePaths.length;
      var promiseArr = []
      for (var i = 0; i < length; i++) {
        //上传文件
        var promise = new Promise((resolve, reject) => {
          var imageUrl = this.data.tempFilePaths[i].split("/");
          var temp = imageUrl[imageUrl.length - 1].split(".");
          var type = temp[temp.length - 1];
          var picUrls = this.data.picUrls;
          var name = this.createNonceStr() + '.' + type;
          wx.cloud.uploadFile({
            cloudPath: 'pics/' + name, //自定义云存储路径
            filePath: this.data.tempFilePaths[i],
            success: res => {
              picUrls.push(res.fileID);
              this.setData({
                picUrls: picUrls //更新data中的 fileID
              })
              resolve(res)
            },
            fail: res => {
              count++;
              wx.hideToast();
              wx.showModal({
                title: '错误提示',
                content: '上传图片失败',
                showCancel: false,
                success: function (res) {}
              })
              reject(err)
            }
          });
        })
        promiseArr.push(promise)
      }
      Promise.all(promiseArr).then(res => {
        console.log(promiseArr)
        //关键步骤：Promise.all()
        //传入Promise数组，当其中所有的Promise执行完后才会执行then()
        let time = this.getTimeStamp()
        db.collection('profHelp').add({
          data: {
            createTime: time,
            content: this.data.input,
            picEnable: this.data.picSwitch,
            picsList: this.data.picUrls,
            price: this.data.price,
            prof: this.data.college,
            title: this.data.title,
            phone: this.data.phone
          }
        }).then(res => {
          console.log()
          wx.hideLoading()
          wx.navigateBack({
            delta: 1,
          })
        })
      })
    }
  },
  getTimeStamp: function () {
    return new Date().getTime()
  },
  createNonceStr: function () {
    var str = "",
      range = 20, //min
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if (true) {
      range = Math.round(Math.random() * (36 - 20)) + 20;
    }
    for (var i = 0; i < range; i++) {
      var pos = Math.round(Math.random() * (arr.length - 1));
      str += arr[pos];
    }
    return str;
  },
})